/*
   Copyright 2010 Johan Hilding

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */


package org.johanhil.flygtider;

import java.util.List;

import org.johanhil.flygtider.flightwatch.FlightWatchBackgroundService;
import org.johanhil.flygtider.flightwatch.FlightWatcher;
import org.johanhil.flygtider.provider.AirportDataProvider;
import org.johanhil.flygtider.provider.FlightInfo;
import org.johanhil.flygtider.provider.impl.StaticAirportDataProvider;
import org.johanhil.flygtider.ui.FlightInfoAdapter;
import org.johanhil.flygtider.ui.FlightListItemClickHandler;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;

/**
 * This is the activity that you get to when the application is launched. 
 */
public class SearchActivity extends Activity {	
	Spinner airportSpinner;
	RadioGroup arrivingDepartingRadioGroup;
	ListView watchedFlightsList;
	Button searchButton;
	private FlightWatcher flightWatcher;
	private AirportDataProvider airportDataProvider;
	private FlightListItemClickHandler flightListItemClickHandler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        airportDataProvider =  new StaticAirportDataProvider(getApplicationContext());
        flightWatcher = new FlightWatcher(getApplicationContext());
        flightListItemClickHandler = new FlightListItemClickHandler(this, flightWatcher, flightWatcher.getWatchedFlights(), true);
        
        findViews();
        setupAdapter();
        setupListeners();
        startBackgroundService();
    }
    
    private void startBackgroundService()
    {
        if (! FlightWatchBackgroundService.isRunning() && flightWatcher.getCount() > 0)
        {
            final Intent serviceIntent = new Intent(this, FlightWatchBackgroundService.class);
            startService(serviceIntent);
        }
    }

    /*
     * Update the watched flights list and hide it if it's empty.
     */
    public void onResume()
    {
    	super.onResume();
    	updateLists();
    }
    
    /**
     * Adds the airport adapter to the spinner.
     */
    private void setupAdapter()
    {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        		android.R.layout.simple_spinner_item,
        		airportDataProvider.getNames());
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        airportSpinner.setAdapter(adapter);
    }
    
    /**
     * Updates the lists 
     */
    private void updateLists()
    {        
    	List<FlightInfo> flights = flightWatcher.getWatchedFlights();
    	FlightInfoAdapter adapter = new FlightInfoAdapter(getApplicationContext(),
                R.layout.flightinfoitem, FlightInfoAdapter.WATCHED_FLIGHTS, flights);
    	
        watchedFlightsList.setAdapter(adapter);
        flightListItemClickHandler.setAdapter(adapter);

        // hide the watched flights list if it's empty
        if (watchedFlightsList.getCount() == 0)
        {
        	findViewById(R.id.watched_flights_layout).setVisibility(View.GONE);
        }
        else
        {
        	findViewById(R.id.watched_flights_layout).setVisibility(View.VISIBLE);
        }
        
        // need to update the click handlers list aswell
        flightListItemClickHandler.setWatchedFlights(flights);
    }
    
    /**
     * Add the listener that handles passing the choices on to FlightListActivity.
     */
    private void setupListeners()
    {
    	searchButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	// start a new activity that lists all the flights
            	Intent flightListIntent = new Intent(v.getContext(), FlightListActivity.class);
            	
            	/*
            	 *  we have to pass the airport index and whether we're looking for 
            	 *  arriving or departing flights.
            	 */
            	
            	// Is this proper?
            	flightListIntent.putExtra("airport", (String) airportSpinner.getSelectedItem());
            	            	
            	if (arrivingDepartingRadioGroup.getCheckedRadioButtonId() == R.id.arriving)
            		flightListIntent.putExtra("arriving", true);
            	else
            		flightListIntent.putExtra("arriving", false);
            	
            	startActivity(flightListIntent);
            }
        });
    	
    	watchedFlightsList.setOnItemClickListener(flightListItemClickHandler);
    	watchedFlightsList.setOnCreateContextMenuListener(flightListItemClickHandler);
    }
    
    /**
     * Assigns the view variables to the right objects.
     */
    private void findViews()
    {
    	watchedFlightsList = (ListView) findViewById(R.id.watched_flights_list);
    	airportSpinner = (Spinner) findViewById(R.id.airportSpinner);
    	arrivingDepartingRadioGroup = (RadioGroup) findViewById(R.id.arrivingdeparting);
    	searchButton = (Button) findViewById(R.id.search_airport);
    }
    
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.searchactivity_options, menu);
	    return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		Dialog dialog = new Dialog(this);

		dialog.setTitle(R.string.about);
		dialog.setContentView(R.layout.about_dialog);

		dialog.show();
		return true;
	}
	
    @Override
    protected void onDestroy() {
        super.onDestroy();
        flightWatcher.close();
    }
}